#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, re
import os, random
#import urllib
import threading,time , shutil
def colortext(col,str):
    if col == 'red':
        return '\033[1;31m%s\033[0m'%str
    elif col == 'pink':
        return '\033[1;35m%s\033[0m'%str
    elif col == 'gold':
        return '\033[1;33m%s\033[0m'%str
    elif col == 'blue':
        return '\033[1;34m%s\033[0m'%str
    else:
        return str
def get_the_file_line(filepath):
    fileid=file(filepath,'r')
    i=0
    while True:
        s=fileid.readline()
        if len(s) !=0:
            i=i+1
        else:
            break
    fileid.close()
    return i
def lastnamesame(s,sduibi,n):
    if s[len(s)-n:len(s)]==sduibi:
        return True
    else:
        return False
def get_the_last_(s):#abcd_aaaa 返回4
    n = 0
    tmp = s
    while tmp.find('_') != -1:
        tmp = tmp[tmp.find('_')+1:]
        n = s.find(tmp)-1
    return n
def noxg(s):
    while s[len(s)-1:len(s)]=='/':
        s=s[0:len(s)-1]
    return s
def check_root():
    pipe=os.popen('/usr/bin/id -u')
    a=pipe.read()
    pipe.close()
    a=a[0:len(a)-1]
    if a=='0':
        return True
    else:
        return False
def get_the_dir_path(dirpath):
    home = os.environ['HOME']
    if dirpath[0:2]=='./':#如果是以./开头的，表示是当前工作目录下的目录
        path=os.getcwd()+'/'+dirpath[2:len(dirpath)]
        return path
    elif dirpath[0:3]=='../':#如果是以../开头的，表示是工作目录上层目录下的目录
        path=os.path.dirname(os.getcwd())+dirpath[2:len(dirpath)]
        return path
    elif dirpath[0:1]=='/':#如果是以/开头的，表示第三个参数即为目录
        path=dirpath
        return path
    elif dirpath[0:1]=='~':
        path = dirpath.replace('~','%s'%home)
        return path
    else:
        path=os.getcwd()+'/'+dirpath
        return path
def get_the_dir_size(path):
    home = os.environ['HOME'] #/home/user
    tmp_file_list = '%s/.tmp/tmp_file_list'%(home)
    os.system('find %s >%s '%(path,tmp_file_list))
    f_line_num = get_the_file_line(tmp_file_list) #获取文件行数
    f = file(tmp_file_list,'r')
    i = 0
    sum = 0
    for i in range(0,f_line_num):
        line_str = f.readline()[:-1]
        if os.path.isfile(line_str):
            #print os.path.getsize(line_str)
            sum = sum + os.path.getsize(line_str)
            #print 'sum=%s'%sum
        elif os.path.isdir(line_str):
            #print os.path.getsize(line_str)
            sum = sum + 4096
    f.close()
    return sum
class timer_install(threading.Thread):
    def __init__(self, (tmpdir,gamux_dirname,truesoftname,the_file_sum), interval):
        threading.Thread.__init__(self)
        self.file_sum = the_file_sum
        self.thread_tmp_file = '%s/installedfilelist'%(tmpdir)
        self.interval = interval
        self.thread_stop = False
    def run(self):
        tmp_sum = 0
        while not self.thread_stop:
            time.sleep(self.interval)
            if os.path.exists(self.thread_tmp_file):
                tmp_num = get_the_file_line(self.thread_tmp_file)
                tmp_sum = float(tmp_num) / float(self.file_sum) * 100
                print '\r%d'%(tmp_sum)+'%' ,
                for i in range(0, int(tmp_sum)):
                    os.write(1, ':')
                sys.stdout.flush()
            if tmp_sum > 99:
                print '\n100%复制数据完成！'
                self.stop()
    def stop(self):
        self.thread_stop = True
class timer(threading.Thread):
    def __init__(self, (tmpdir,gamux_dirname,truesoftname,sizesum), interval):
        threading.Thread.__init__(self)
        self.gamux_size_sum = sizesum
        self.thread_tmp_file = '%s/%s.tmp'%(tmpdir,gamux_dirname)
        self.interval = interval
        self.thread_stop = False
    def run(self):
        tmp_sum = 0
        while not self.thread_stop:
            time.sleep(self.interval)
            if os.path.exists(self.thread_tmp_file):
                tmp_size = os.stat(self.thread_tmp_file).st_size
                tmp_sum = float(tmp_size) / float(self.gamux_size_sum) * 100
                print '\r%d'%(tmp_sum)+'%' ,
                for i in range(0, int(tmp_sum)):
                    os.write(1, ':')
                sys.stdout.flush()
            if tmp_sum > 99:
                print '\n100%解压完成！'
                self.stop()
    def stop(self):
        self.thread_stop = True
class GAMUX:
    def mh_list_the_pack(self,str):
        ls = os.listdir(self.gamuxdir)
        lss = []
        lsss = []
        print colortext('gold','【包含\'%s\'的游戏列表】'%str + colortext('pink','（区分大小写）'))
        if len(ls) == 0:
            print colortext('red','（空）\n未找到！')
            exit(0)
        for soft in ls:
            softpath = self.gamuxdir + '/%s'%soft
            if os.path.isdir(softpath):
                if str in soft:
                    info  = self.gamuxdir + '/' + soft + '/info'
                    filelist  = self.gamuxdir + '/' + soft + '/filelist'
                    #print info
                    #print filelist
                    if os.path.exists(info) and os.path.exists(filelist):
                        lsss.append(soft)
                        fileid = file(info,'r')
                        for i in range(0,get_the_file_line(info)):
                            s = fileid.readline()
                            s = s[:-1]
                            ver = s[4:]
                            if s[:4] == 'ver=':
                                lss.append(soft + '_%s'%ver)
                                print '【%s】游戏名称:'%(lsss.index(soft)+1) + colortext('gold',soft) + '------->版本号：' + colortext('gold',ver)
                        fileid.close()
        #print '\033[1;31m提示：若要删除游戏，请在普通权限下执行gamux -r softname（不带版本号）\033[0m'
        if len(lss) == 0:
            print colortext('red','（空）\n未找到！')
            exit(0)
        else:
            print colortext('pink','提示：若要删除游戏，请在普通权限下执行gamux -r softname（不带版本号）')
    def list_the_pack(self):
        ls = os.listdir(self.gamuxdir)
        lss = []
        lsss = []
        print colortext('gold','【已安装列表】')
        if len(ls) == 0:
            print colortext('red','（空）\n未安装游戏！')
            exit(0)
        for soft in ls:
            softpath = self.gamuxdir + '/%s'%soft
            if os.path.isdir(softpath):
                info  = self.gamuxdir + '/' + soft + '/info'
                filelist  = self.gamuxdir + '/' + soft + '/filelist'
                #print info
                #print filelist
                if os.path.exists(info) and os.path.exists(filelist):
                    lsss.append(soft)
                    fileid = file(info,'r')
                    for i in range(0,get_the_file_line(info)):
                        s = fileid.readline()
                        s = s[:-1]
                        ver = s[4:]
                        if s[:4] == 'ver=':
                            lss.append(soft + '_%s'%ver)
                            print '【%s】游戏名称:'%(lsss.index(soft)+1) + colortext('gold',soft) + '------->版本号：' + colortext('gold',ver)
                    fileid.close()
        print colortext('pink','提示：若要删除游戏，请在普通权限下执行gamux -r softname（不带版本号）')
        #print '\033[1;31m提示：若要删除游戏，请在普通权限下执行gamux -r softname（不带版本号）\033[0m'
        if len(lss) == 0:
            print colortext('red','（空）\n未安装游戏！')
            exit(0)
    def removepackges(self,argv2):
        if len(argv2.split('/')) != 1:
            print colortext('red','错误:目标应为软件名不含/.如gamux -r cs2d')
            exit(0)
        else:
            remove_basename = argv2
            softhomepath = self.gamuxdir + '/%s'%(argv2)
            if os.path.exists(softhomepath):
                remove_filelist=softhomepath+'/filelist'
                print '提示：正在执行删除软件包...'
                fileid=file(remove_filelist,'r')
                s=fileid.readline()
                if len(s)!=1:
                    s=s[0:-1]
                    shutil.rmtree(s)
                fileid.close()
                shutil.rmtree(softhomepath)
                desktop_file = self.applications + '/%s.desktop'%(argv2)
                os.system('rm %s'%(desktop_file))
                print '提示：删除完成！'
                return 'iok'
            else:
                print '该软件包未安装！注意删除软件包时不需要加.gamux'
                #print home_remove_basename
                exit(0)
            self.echohelp()
    def update(self):
        server_ver_addr = 'http://gamux-dev.qiniudn.com/ver'
        server_gamux_addr = 'http://gamux-dev.qiniudn.com/gamux'
        tmp_ver = '/tmp/ver'
        os.system('wget -O %s %s'%(tmp_ver,server_ver_addr))
        if os.path.exists(tmp_ver):
            f = file(tmp_ver,'r')
            ver = int(f.readline())
            f.close()
            os.system('rm %s'%(tmp_ver))
            if self.ver == ver:
                print '提示:你本地gamux已经为最新版本!'
            elif self.ver > ver:
                print '提示：你牛！比服务器新！'
            elif self.ver < ver:
                tmp_gamux = '/tmp/gamux'
                os.system('wget -O %s %s'%(tmp_gamux,server_gamux_addr))
                if os.path.exists(tmp_gamux):
                    os.system('cp %s /usr/bin/'%(tmp_gamux))
                    os.system('chmod +x /usr/bin/gamux')
                    os.system('rm %s'%(tmp_gamux))
                    os.system('/usr/bin/gamux -v')
                    print '提示:更新完成!'
    def print_help(self):
        print '\n使用方法: gamux -[birx]  [dir or *.gamux]\n'
        print '命令选项:\t使用说明:\n'
        print '-b\t\t将文件夹打包成gamux 如：gamux -b testdir'
        print '-i\t\t安装gamux包 如：gamux -i test.gamux'
        print '-r\t\t卸载gamux包 如：gamux -r test'
        print '-x\t\t解压gamux包 如：gamux -x test.gamux'
        print '-v\t\t查看gamux版本号'
        print '--update\t更新gamux主程序(需要root权限) 如：sudo gamux --update'
        print '--uninstall\t卸载gamux主程序 如：gamux --uninstall'
        print '--help\t\t查看帮助文档'
    def fourfilesexists(self,dirpath):#检测五个控制脚本是否存在
        self.fatherdirpath=os.path.dirname(dirpath)
        self.dirpath_info=self.fatherdirpath+'/info'
        if os.path.exists(self.dirpath_info)==False:
            print '错误：info文件不存在！该文件包含该软件包的基本信息!'
            os.system('cat %s/info'%(self.gamuxdir))
            return False
        else:
			return True
    def dopackges(self,argv2):
        dirpath=get_the_dir_path(argv2)#首先要获取打包文件夹地完整路径
        dirpath=noxg(dirpath)
        softname=os.path.basename(dirpath)
        if os.path.exists(dirpath)==False:
            print '错误：目标不存在！'
        elif os.path.isdir(dirpath)==False:
            print '错误：目标不是一个文件夹'
        elif self.fourfilesexists(dirpath)==False:
            print '错误：%s内需要info文件！退出！'%(self.fatherdirpath)
            exit(0)
        else:
            print '提示：正在打包。。。'
            infopath=os.path.dirname(dirpath)+'/info'
            filelist_for_line_num = os.path.dirname(dirpath)+'/filelist_for_line_num'
            os.system('find %s >> %s'%(dirpath,filelist_for_line_num))
            f = file(infopath,'r')
            i = 0
            for i in range(0,4):
                s = f.readline()
                if s[0:4] == 'ver=':
                    ver = s[4:-1]
                    if len(ver) == 0:
                        tmpkz = '.tmp'
                    else:
                        tmpkz = '_%s.tmp'%ver
            f.close()
            os.chdir(dirpath)
            tmppath=noxg(os.path.dirname(dirpath))+'/%s%s'%(softname,tmpkz)
            os.system('tar -cjf %s ./*'%tmppath)
            tmpfilename=os.path.basename(tmppath)
            gamname=tmpfilename[0:len(tmpfilename)-4] + '.gamux'
            self.fatherdirpath=noxg(self.fatherdirpath)
            gampath=self.fatherdirpath+'/'+gamname
            if os.path.exists(tmppath):
                os.chdir(self.fatherdirpath)
                if os.path.exists('%s/logo.png'%self.fatherdirpath) == False:
                    os.system('wget http://blog.tu7u.com/gamux/logo.png')
                if os.path.exists('%s/s1.png'%self.fatherdirpath) == False:
                    os.system('wget http://blog.tu7u.com/gamux/s1.png')
                if os.path.exists('%s/s2.png'%self.fatherdirpath) == False:
                    os.system('wget http://blog.tu7u.com/gamux/s2.png')
                os.system('tar -cjf %s ./%s ./info ./filelist_for_line_num ./s1.png ./s2.png ./logo.png'%(gamname,tmpfilename))
                shutil.rmtree((tmpfilename))
                if os.path.exists(os.getcwd()+'/%s'%gamname):
                    os.system('chmod +x %s'%(gampath))
                    print '打包完成！\ngamux包位于%s'%gampath
                    return 'bok'
    def installpackges(self,argv2):
        gamux_file_path=get_the_dir_path(argv2)#首先要获取完整路径#/abc/abc.gamux
        if os.path.exists(gamux_file_path)==False:
            print '错误：目标不存在'
            exit(0)
        if lastnamesame(gamux_file_path,'gamux',5):
            gamux_size = os.stat(gamux_file_path).st_size
            gamux_file_path_name=os.path.basename(gamux_file_path)#abc.gam
            gamux_dirname=gamux_file_path_name[0:len(gamux_file_path_name)-6]#abc_222
            n = get_the_last_(gamux_dirname)#获取_位置
            if n == 0:
                truesoftname = gamux_dirname
                ver = '0'
            else:
                truesoftname = gamux_dirname[:n]
                ver = gamux_dirname[n+1:]
            filenamelist = os.listdir('%s'%(self.gamuxdir))
            i = 0
            l = len(filenamelist)
            for i in range(0,l):
                if truesoftname == filenamelist[i]:
                    f = file('%s/%s/info'%(self.gamuxdir,filenamelist[i]),'r')
                    ii = 0
                    for ii in range(0,4):
                        s = f.readline()
                        if s[0:4] == 'ver=':
                            installedver = s[4:-1]
                            if len(installedver) == 0:
                                installedver = '0'
                    f.close()
                    if int(ver) < int(installedver):
                        print '已安装版-->%s_%s'%(truesoftname,installedver)
                        print '目标版本-->%s'%gamux_dirname
                        print colortext('red','提示:你想要安装的版本比已经存在的版本还低!')
                        exit(0)
                    elif int(ver) == int(installedver):
                        print colortext('blue','提示：该版本游戏已经安装,可使用-r选项将其缷载。')
                        exit(0)
                    else:
                        yorn = raw_input('\033[1;35m本机已经安装了较低版本的%s,是否继续安装新版本?y/n:\033[0m'%truesoftname)
                        if yorn == 'y' or yorn == 'Y' or yorn == 'yes':
                            os.system('rm -r %s/%s'%(self.gamuxdir,filenamelist[i]))
                        else:
                            print '\033[1;31m提示:未安装!\033[0m'
                            exit(0)
            tmpdir='%s/%s'%(self.tmp_path,truesoftname)
            homesoftdir=self.gamuxdir+'/%s'%truesoftname
            if os.path.exists(homesoftdir) == False:
                os.mkdir(homesoftdir)
            else:
                shutil.rmtree(homesoftdir)
            if os.path.exists(tmpdir)==False:
                os.mkdir(tmpdir)
            else:
                shutil.rmtree(tmpdir)
                os.mkdir(tmpdir)
            print '提示：正在解压%s...'%gamux_dirname
            packtimer = timer((tmpdir,gamux_dirname,truesoftname,gamux_size),0.1)
            packtimer.setDaemon(True)
            packtimer.start()
            os.system('tar -xjf %s -C %s'%(gamux_file_path,tmpdir))
            packtimer.stop()
            time.sleep(0.5)
            tmpinfo=tmpdir+'/info'
            tmpfilelist = tmpdir + '/filelist_for_line_num'
            if os.path.exists(tmpfilelist) == False:
                shutil.rmtree(homesoftdir)
                shutil.rmtree(tmpdir)
                print colortext('red','%s不存在，请检查*.gamux包是否完整！'%tmpfilelist)
                print colortext('red','请重新下载完整包后再安装！')
                exit(0)
            tmpypk0=tmpdir+'/%s'%gamux_file_path_name
            tmpypk=tmpypk0[0:len(tmpypk0)-6]+'.tmp'
            print '提示：正在安装%s数据包...'%gamux_dirname
            the_file_num_sum = get_the_file_line(tmpfilelist)
            installtimer = timer_install((tmpdir,gamux_dirname,truesoftname,the_file_num_sum),0.1)
            installtimer.setDaemon(True)
            installtimer.start()
            user_diy_path = '%s/%s'%(self.all_game_home,truesoftname)
            while True:
                user_entry = raw_input('请输入安装路径,默认为\'%s\'.默认请按y回车:'%(user_diy_path))
                if user_entry == 'y' or user_entry.replace(' ','') == '':
                    install_path = user_diy_path
                    break
                elif os.path.exists(get_the_dir_path(user_entry)):
                    if os.path.isdir(get_the_dir_path(user_entry)):
                        install_path = get_the_dir_path(user_entry)
                        break
                else:
                    user_entry = get_the_dir_path(user_entry)
                    os.mkdir(user_entry)
                    install_path = user_entry
                    break
            if os.path.exists(install_path) == False:
                os.mkdir(install_path)
            os.system('tar -xvjf %s -C %s > %s/installedfilelist'%(tmpypk,install_path,tmpdir))
            installtimer.stop()
            filelist = homesoftdir + '/filelist'
            os.system('find %s >> %s'%(install_path,filelist))
            os.system('cp %s %s'%(tmpinfo ,homesoftdir))
            shutil.rmtree(tmpdir)
######################此处为修改运行文件,将安装目录写入运行文件###################start
            f_run_file = install_path + '/' + truesoftname
            f_run_file_ls = []
            f_run_id = file(f_run_file,'r')
            i = 0
            for i in range(0,get_the_file_line(f_run_file)):
                f_run_line_str = f_run_id.readline()
                if f_run_line_str[0:13] == 'install_path=':
                    f_run_line_str = 'install_path=%s\n'%(install_path)
                f_run_file_ls.append(f_run_line_str)
            f_run_id.close()
            f_run_id = file(f_run_file,'w')
            for j in range(0,len(f_run_file_ls)):
                f_run_id.write(f_run_file_ls[j])
            f_run_id.close()
            os.system('chmod +x %s'%f_run_file)
######################此处为修改运行文件,将安装目录写入运行文件###################end
######################此处为修改desktop文件###################start
            f_run_file = install_path + '/%s.desktop'%truesoftname
            f_run_file_ls = []
            f_run_id = file(f_run_file,'r')
            i = 0
            for i in range(0,get_the_file_line(f_run_file)):
                f_run_line_str = f_run_id.readline()
                if f_run_line_str[0:5] == 'Exec=':
                    f_run_line_str = 'Exec=%s/%s\n'%(install_path,truesoftname)
                if f_run_line_str[0:5] == 'Icon=':
                    f_run_line_str = 'Icon=%s/%s.png\n'%(install_path,truesoftname)
                f_run_file_ls.append(f_run_line_str)
            f_run_id.close()
            f_run_id = file(f_run_file,'w')
            for j in range(0,len(f_run_file_ls)):
                f_run_id.write(f_run_file_ls[j])
            f_run_id.close()
            os.system('cp %s %s'%(f_run_file,self.applications))
######################此处为修改运行文件###################end
            print colortext('gold','提示：%s安装完成！'%gamux_dirname)
            return 'iok'
        else:
            print colortext('red','错误：目标不是gamux包')
            exit(0)
    def xpackges(self,argv2):
        filepath = get_the_dir_path(argv2)#首先要获取完整路径#/abc/abc.gam
        basename = os.path.basename(filepath)#abc.gamux
        old = basename[:-6]
        n = get_the_last_(basename)
        if n == 0:
            filename = basename[:-6]
        else:
            filename = basename[:n]#abc
        if os.path.exists(filepath)==False:
            print colortext('red','错误：目标不存在')
            exit(0)
        if lastnamesame(filepath,'gamux',5):
            dirpath = os.path.dirname(filepath)+'/%s'%filename
            if os.path.exists(dirpath) == False:
                os.mkdir(dirpath)
            print '提示：开始解压！'
            os.system('tar -xjf %s -C %s'%(filepath,dirpath))
            tmppath = dirpath + '/%s.tmp'%old
            dirpath = dirpath +'/%s'%filename
            if os.path.exists(dirpath) == False:
                os.mkdir(dirpath)
            os.system('tar -xjf %s -C %s'%(tmppath,dirpath))
            os.system('rm %s'%tmppath)
            dirpath = os.path.dirname(filepath)+'/%s'%filename
            os.system('chmod 777 %s'%dirpath)
            print colortext('pink','提示：解压完成！')
            exit(0)
        else:
            print colortext('red','错误：只能解压gamux包！')
    def checkversion(self):
        print '版本号:' + colortext('gold',self.ver)
        print '作  者:' + colortext('gold','那一角')
        print 'E-mail:' + colortext('gold','1259809558@qq.com')
        print '主  页:' + colortext('gold','http://blog.tu7u.com/gamux-dev')
    def uninstall(self):
        a = random.randint(1,10)
        b = random.randint(1,10)
        c = a + b
        num = raw_input(colortext('pink','请输入计算结果:%s'%a + '+' + '%s='%b))
        if re.match('^[0-9]+$',num) == None:
            print colortext('red','未卸载!')
            exit(0)
        else:
            num = int(num)
        if num != c:
            print colortext('red','未卸载!')
            exit(0)
        elif num == c:
            yesorno = raw_input(colortext('red','卸载后将无法查看已经安装的游戏确定要卸载gamux吗？yes/no:'))
            if yesorno == 'yes':
                os.system('sudo rm /usr/bin/gamux')
                os.system('rm -r ~/.gamux')
                os.system('rm -r ~/.tmp')
                print colortext('gold','卸载完成!')
                exit(0)
            else:
                print colortext('red','未卸载!')
                exit(0)
    def main(self):
        self.ver = 2014031318
        self.home = os.environ['HOME'] #/home/user
        self.share = self.home + '/.local/share'
        self.applications = self.share + '/applications'
        self.gamuxdir = self.home + '/.gamux'
        if os.path.exists(self.gamuxdir)==False:
            os.mkdir(self.gamuxdir)
        self.tmp_path = self.home + '/.tmp'
        if os.path.exists(self.tmp_path)==False:
            os.mkdir(self.tmp_path)
        self.all_game_home = self.home + '/games'
        if os.path.exists(self.all_game_home)==False:
            os.mkdir(self.all_game_home)
        if len(sys.argv) == 3:
            argv0=sys.argv[0]
            argv1=sys.argv[1]
            argv2=sys.argv[2]
            if (argv1 == '-b'):
                self.dopackges(argv2)
            elif (argv1 == '-i'):
                self.installpackges(argv2)
            elif (argv1 == '-r'):
                self.removepackges(argv2)
            elif (argv1 == '-x'):
                self.xpackges(argv2)
            elif (argv1 == '-l'):
                self.mh_list_the_pack(argv2)
                exit(0)
            elif sys.argv[1] != '-v':
                self.print_help()
                exit(0)
            elif sys.argv[1] != '--update':
                self.print_help()
                exit(0)
            elif sys.argv[1] != '--uninstall':
                self.print_help()
                exit(0)
        if len(sys.argv) > 1:
            if sys.argv[1] == '-v':
                self.checkversion()
                exit(0)
            elif sys.argv[1] == '-l':
                self.list_the_pack()
                exit(0)
            elif sys.argv[1] == '--uninstall':
                self.uninstall()
                exit(0)
            elif sys.argv[1] == '--update':
                if check_root():
                    self.update()
                    exit(0)
                else:
                    print colortext('red','错误：更新需要root权限！')
                    exit(0)
        if len(sys.argv) != 3 or sys.argv[1] == '--help':
            self.print_help()
if __name__=='__main__':
	gamux=GAMUX()
	gamux.main()
